package sql

import (
	"URLshortener/internal/model"
	"context"
	"xorm.io/xorm"
)

type urlDaoImpl struct {
	engine *xorm.Engine
}

func NewUrlDao(engine *xorm.Engine) UrlDao {
	return &urlDaoImpl{engine: engine}
}

func (d *urlDaoImpl) FindByOriginalUrl(ctx context.Context, originalUrl string) (*model.Url, bool, error) {
	var url model.Url
	has, err := d.engine.Context(ctx).Where("original_url = ?", originalUrl).Get(&url)
	return &url, has, err
}

func (d *urlDaoImpl) FindByShortCode(ctx context.Context, shortCode string) (*model.Url, error) {
	var url model.Url
	_, err := d.engine.Context(ctx).Where("short_code = ?", shortCode).Get(&url)
	return &url, err
}

func (d *urlDaoImpl) SaveUrl(ctx context.Context, url *model.Url) error {
	_, err := d.engine.Context(ctx).Insert(url)
	return err
}

func (d *urlDaoImpl) DeleteUrl(ctx context.Context, shortCode string) error {
	_, err := d.engine.Context(ctx).Where("short_code = ?", shortCode).Delete(&model.Url{})
	return err
}

func (d *urlDaoImpl) ExistShortCode(ctx context.Context, shortCode string) (bool, error) {
	return d.engine.Context(ctx).Exist(&model.Url{ShortCode: shortCode})
}
